package com.byedu.course;

import com.byedu.base.BaseService;
import com.byedu.domain.course.*;
import com.byedu.domain.course.vo.CourseBuyVO;
import com.byedu.domain.course.vo.CourseVO;
import com.byedu.domain.course.vo.LibraryVO;
import com.byedu.domain.focus.BResultDO;
import com.byedu.mapper.course.CourseMapper;
import com.byedu.mapper.course.LibraryMapper;
import com.byedu.mapper.course.UserCourseMapper;
import com.byedu.mapper.course.UserLibraryMapper;
import com.byedu.model.enums.IndustryEnum;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created by jason on 2017/4/25.
 */
@Service
public class CourseService extends BaseService{

	@Autowired
	private CourseMapper courseMapper;

    @Autowired
    private LibraryMapper libraryMapper;

    @Autowired
    private UserCourseMapper userCourseMapper;

    @Autowired
    private UserLibraryMapper userLibraryMapper;

    /**
     * @description 获取课程列表
     * @author chenxigui
     * @return
     */
    public List<CourseVO> listallCourses() {

        return convertDoListToVoList(courseMapper.listCourses(),null);
    }

    public List<CourseBuyVO> listallBuyCourses() {

        return convertDoListToBuyVOList(courseMapper.listCourses());
    }
    public int saveCourses(CourseDO courseDO) {

        return courseMapper.saveCourse(courseDO);
    }

    /**
     * @description 获取课程列表
     * @author chenxigui
     * @return
     */
    public List<CourseVO> listCoursesbyIndustry(String industry) {

        return convertDoListToVoList(courseMapper.listCoursesbyIndustry(industry),null);
    }

    public List<CourseBuyVO> listCourseBuysbyIndustry(String industry) {

        return convertDoListToBuyVOList(courseMapper.listCoursesbyIndustry(industry));
    }
    /**
     * @description 获取课程列表
     * @author chenxigui
     * @return
     */
    public List<CourseBuyVO> listmineCourses(String userId) {

        return convertDoListToBuyVOList(courseMapper.listCoursesByUserId(userId));
    }

    /**
     * @description 获取课程列表
     * @author chenxigui
     * @return
     */
    public List<CourseBuyVO> listhotCourses() {

        return convertDoListToBuyVOList(courseMapper.listhotCoursesByUserId());
    }

    /**
     * @description 获取课程列表
     * @author chenxigui
      * @return
     */
    public Map<String,List<CourseVO>> listCourses(String userId) {
        List<UserLibraryDO> userLibraryList = userLibraryMapper.getUserLibrarybyUserId(userId);
        List<CourseDO> allcourses = courseMapper.listCourses();
        List<CourseVO> payCourses = convertDoListToVoList(courseMapper.listCoursesByUserId(userId),userId);

        List<CourseCount> cidcount =  userCourseMapper.getcidcount();
//        List<CourseCount> uidcount =  userCourseMapper.getuidcount();
        List<CourseCount> rankcount =  userCourseMapper.getrankcount();

        Map<Integer, List<LibraryDO>> libraryGroup = mapLibraries(allcourses);
        //设置我购买的
        if(CollectionUtils.isNotEmpty(payCourses)){
            for (int i = 0; i < allcourses.size(); i++) {
                for (int j = 0; j < payCourses.size(); j++) {
                    if(allcourses.get(i).getId() == payCourses.get(j).getId()){
                        allcourses.get(i).setPay(true);
                    }
                }
            }
        }

        //分类
        Map<String,List<CourseVO>>  cousMap = new HashMap<String,List<CourseVO>>();
        for(IndustryEnum industry : IndustryEnum.values()){
            List<CourseVO> industryList = new ArrayList<CourseVO>();
            for (int i = 0; i < allcourses.size(); i++) {
                    if(allcourses.get(i).getIndustry().equals(industry.name())){
                        CourseVO courseVO = new CourseVO(allcourses.get(i), libraryGroup.get(allcourses.get(i).getId()),userLibraryList);

                        //设置做题人数
                        for(CourseCount cid : cidcount){
                            if(courseVO.getId() == cid.getCid()){
                                courseVO.setUseNum(cid.getCont());
                            }
                       }
                        //设置排行、进度
                        int rant = 0;
                        for(CourseCount rankid : rankcount){
                            if(courseVO.getId() == rankid.getCid()){
                                rant++;
                                if(userId.equals(rankid.getUid())){
                                    if (libraryGroup.get(courseVO.getId()).size()>0){
                                        courseVO.setProcess(rankid.getCont() * 100/ libraryGroup.get(courseVO.getId()).size());
                                        System.out.println("rank:"+rankid.getCont());
                                        System.out.println("libraryGroup:"+libraryGroup.get(courseVO.getId()).size());
                                    }else{
                                        courseVO.setProcess(0);
                                    }
                                    courseVO.setRank(rant);
                                }
                            }

                        }
                        industryList.add(courseVO);
                    }
                }
            cousMap.put(industry.name(),industryList);
        }
        //排序

        return cousMap;
    }
	/**
	 * @description 获取课程列表
	 * @author chenxigui
	 * @param userId
	 * @return
	 */
	public List<CourseDO> listCoursesByUserId(String userId) {
        Objects.requireNonNull(userId, "userId = " + userId);
        List<CourseDO> courseDOList = courseMapper.listCoursesByUserId(userId);
        List<CourseCount> rankcount =  userCourseMapper.getrankcount();
        List<CourseCount> countis = courseMapper.countCourseLibraris();
        for (int j = 0; j < courseDOList.size(); j++) {
            courseDOList.get(j).setPay(true);

            for(CourseCount rankid : rankcount){
                for(CourseCount counti : countis) {
                    if (courseDOList.get(j).getId() == rankid.getCid() && courseDOList.get(j).getId() == counti.getCid()) {
                        if (userId.equals(rankid.getUid())) {
                            if (counti.getCont()>0) {
                                courseDOList.get(j).setProcess(rankid.getCont() * 100 / counti.getCont());

                            } else {
                                courseDOList.get(j).setProcess(0);
                            }
                        }
                    }
                }

            }
        }
        return courseDOList;
    }

    public CourseDO getCourseById(String courseId,String userId) {
        UserCourseDO userCourseDO = userCourseMapper.getbayCourse(userId, courseId);
        CourseDO courseDO =courseMapper.getCourseById(courseId);
        if(userCourseDO !=null){
            courseDO.setPay(true);
        }
        return courseDO;
    }

    private List<CourseBuyVO> convertDoListToBuyVOList(List<CourseDO> courseDOs) {
        if (CollectionUtils.isNotEmpty(courseDOs)) {
            List<CourseBuyVO> courseVOList = new ArrayList<CourseBuyVO>();
//            Map<Integer, List<LibraryDO>> libraryGroup = mapLibraries(courseDOs);
            for (CourseDO courseDO : courseDOs) {
//                List<LibraryDO> libraryDOs = libraryGroup.get(courseDO.getId());
//                CourseBuyVO courseVO = new CourseBuyVO(courseDO, libraryDOs);
                CourseBuyVO courseVO = new CourseBuyVO(courseDO, null);
                courseVOList.add(courseVO);
            }

            return courseVOList;
        }

        return null;
    }

    private List<CourseVO> convertDoListToVoList(List<CourseDO> courseDOs,String userId) {
        if (CollectionUtils.isNotEmpty(courseDOs)) {
            List<CourseVO> courseVOList = new ArrayList<CourseVO>();
            Map<Integer, List<LibraryDO>> libraryGroup = mapLibraries(courseDOs);
            //查询用户使用情况
            List<BResultDO> numbrList = libraryMapper.getCourseCountById();
            //查询排行情况
            List<BResultDO> rankbrList = libraryMapper.getCourseCountByUserId();
            //查询每个题库包括多少试卷数
            List<BResultDO> countbrList = libraryMapper.getAllCourseCount();
            List<UserLibraryDO> userLibraryList = userLibraryMapper.getUserLibrarybyUserId(userId);

            for (CourseDO courseDO : courseDOs) {
                List<LibraryDO> libraryDOs = libraryGroup.get(courseDO.getId());
                CourseVO courseVO = new CourseVO(courseDO, libraryDOs,userLibraryList);
                for(BResultDO bResultDO : numbrList){
                    if(bResultDO.getCourseId() == courseVO.getId()){
                        courseVO.setUseNum(bResultDO.getCount());
                    }
                }

                int allquestNum = 0 ;
                for(BResultDO bResultDO : countbrList){
                    if(bResultDO.getCourseId() == courseVO.getId()){
                        allquestNum = bResultDO.getCount();
                    }
                }
                for(int i = 0; i < rankbrList.size(); i++){
                    if(rankbrList.get(i).getCourseId() == courseVO.getId() && rankbrList.get(i).getUserId().equals(userId)){
                        courseVO.setRank(i+1);
                        if(allquestNum != 0) {
                            courseVO.setProcess((rankbrList.get(i).getCount() * 100) / allquestNum);
                        }
                    }
                }
                courseVOList.add(courseVO);
            }
            return courseVOList;
        }

        return null;
    }

    /**
     * 批量获取题库(试卷),按课程ID分组
     * @param courseDOs
     * @return
     */
    private Map<Integer, List<LibraryDO>> mapLibraries(List<CourseDO> courseDOs) {
        List<Integer> courseIds = new ArrayList<>();
        for (CourseDO courseDO : courseDOs) {
            courseIds.add(courseDO.getId());
        }
        //批量获取library的信息
        List<LibraryDO> libraryDOs =  libraryMapper.listLibrariesByCourseIdList(courseIds);
        Map<Integer, List<LibraryDO>> libraryGroup = new HashMap<>();
        for (LibraryDO libraryDO : libraryDOs) {
            List<LibraryDO> libraries = libraryGroup.get(libraryDO.getCourseId());
            if (libraries != null) {
                libraries.add(libraryDO);
            } else {
                libraries = new ArrayList<>();
                libraries.add(libraryDO);
                libraryGroup.put(libraryDO.getCourseId(), libraries);
            }
        }

        return libraryGroup;
    }

    public List<LibraryVO> listLibrariesByCourseId(Integer courseId) {
        return convertLibraryDoListToVoList(libraryMapper.listLibrariesByCourseId(courseId));
    }

    public List<LibraryVO> convertLibraryDoListToVoList(List<LibraryDO> libraryDOList) {
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(libraryDOList)) {
            List<LibraryVO> libraryVOList = new ArrayList<LibraryVO>();
            for (LibraryDO libraryDO : libraryDOList) {
                LibraryVO libraryVO = new LibraryVO();
                try {
                    BeanUtils.copyProperties(libraryVO, libraryDO);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                libraryVOList.add(libraryVO);
            }

            return libraryVOList;
        }

        return null;
    }

    public int delCourse(int id) {
        return courseMapper.delCourse(id);
    }
}
